<template>
  <div>
    <el-form :inline="true">
      <el-form-item>
        <el-input
            v-model="searchForm.orderNum"
            placeholder="订单号"
            clearable
        >
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button @click="getOrdersList">搜索</el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="dialogVisible = true" v-if="hasAuth('sys:orders:save')">新建</el-button>
      </el-form-item>
      <el-form-item>
        <el-popconfirm title="这是确定批量删除吗？" @confirm="delHandle(null)">
          <el-button type="danger" slot="reference" :disabled="delBtlStatu" v-if="hasAuth('sys:user:delete')">批量删除
          </el-button>
        </el-popconfirm>
      </el-form-item>
        <el-form-item>
          <el-upload
              :multiple="false"
              accept=".xls,.xlsx"
              ref="upload"
              action="#"
              :before-upload="beforeUpload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :on-change="handleChange"
              :http-request="uploadHttpRequest"
              :limit="1"
              :file-list="fileList"
              :auto-upload="false">
            <el-button slot="trigger" type="primary">选取文件</el-button>
            <el-button type="primary" @click="submitUpload">导入Excel</el-button>
            <div slot="tip" class="el-upload__tip">一次只能导入一个Excel文件</div>
          </el-upload>
        </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="getOrdersExcel">导出Excel</el-button>
      </el-form-item>

    </el-form>
    <!--主体表-->
    <el-table
        ref="multipleTable"
        :data="tableData"
        tooltip-effect="dark"
        style="width: 100%"
        border
        stripe
        @selection-change="handleSelectionChange">

      <el-table-column
          type="selection"
          width="55">
      </el-table-column>

      <el-table-column
          prop="orderNum"
          label="订单号"
          width="155">
      </el-table-column>

      <el-table-column
          prop="orderitems"
          width="70px"
          label="订单项">

        <template slot-scope="scope">
          <el-button type="text" @click="selectOrderitems(scope.row.orderId)">详情</el-button>
        </template>
      </el-table-column>

      <el-table-column
          prop="orderCreater"
          label="订单创建者"
          width="100">
      </el-table-column>

      <el-table-column
          prop="orderCustomerid"
          label="订单客户id"
          width="70">
      </el-table-column>

      <el-table-column
          prop="orderTotalmoney"
          label="订单总金额"
          width="70">
      </el-table-column>

      <el-table-column
          prop="created"
          width="170"
          label="订单创建时间"
      >
      </el-table-column>

      <el-table-column
          prop="statu"
          label="状态"
          width="150">
        <template slot-scope="scope">
          <el-tag size="small" v-if="scope.row.statu === 3" type="success">订单已完成</el-tag>
          <el-tag size="small" v-if="scope.row.statu === 2" type="info">已确认出库,待订单结束</el-tag>
          <el-tag size="small" v-if="scope.row.statu === 1" type="primary">已审核,待确认出库</el-tag>
          <el-tag size="small" v-else-if="scope.row.statu === 0" type="danger">已创建,待审核</el-tag>
        </template>
      </el-table-column>

      <el-table-column
          prop="orderChecker"
          label="订单审核人的用户"
          width="70">
      </el-table-column>
      <el-table-column
          prop="orderConfirmer"
          label="订单确认者的用户"
          width="70">
      </el-table-column>
      <el-table-column
          prop="orderEnder"
          label="订单结束者的用户"
          width="70">
      </el-table-column>

      <el-table-column
          prop="orderCheckedtime"
          width="170"
          label="订单审核时间"
      >
      </el-table-column>
      <el-table-column
          prop="orderConfirmtime"
          width="170"
          label="订单确认时间"
      >
      </el-table-column>

      <el-table-column
          prop="orderEndtime"
          width="170"
          label="订单结束时间"
      >
      </el-table-column>
      <el-table-column
          prop="remark"
          width="120"
          label="备注"
      >
      </el-table-column>
      <el-table-column
          prop="icon"
          width="260px"
          label="操作">

        <template slot-scope="scope">

          <el-button type="text" @click="editHandle(scope.row.orderId)">编辑</el-button>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="这是一段内容确定删除吗？" @confirm="delHandle(scope.row.orderId)">
              <el-button type="text" slot="reference">删除</el-button>
            </el-popconfirm>
          </template>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="确定审核通过吗？" @confirm="checkHandle(scope.row.orderId)">
              <el-button type="text" slot="reference">订单审核</el-button>
            </el-popconfirm>
          </template>
          <el-divider direction="vertical"></el-divider>

          <template>
            <el-popconfirm title="订单确认通过吗？" @confirm="endHandle(scope.row.orderId)">
              <el-button type="text" slot="reference">订单结束</el-button>
            </el-popconfirm>
          </template>

        </template>
      </el-table-column>

    </el-table>

    <!--订单项详情对话框-->
    <el-dialog
        title="订单项"
        :visible.sync="dialogVisible_orderitems">

      <el-table
          :data="tableData_Dialog"
          tooltip-effect="dark">

        <el-table-column
            prop="goodName"
            label="产品名">
        </el-table-column>

        <el-table-column
            prop="goodQuantity"
            label="产品数量">
        </el-table-column>

        <el-table-column
            prop="totalPrice"
            label="一个订单项总金额">
        </el-table-column>

      </el-table>


    </el-dialog>
    <!--订单新增或编辑对话框-->
    <el-dialog
        title="订单新建或编辑"
        :visible.sync="dialogVisible"
        :before-close="handleClose">

      <el-form :model="editForm" :rules="editFormRules" ref="editForm">
        <el-form-item label="备注" prop="remark" label-width="100px">
          <el-input
              type="textarea"
              v-model="editForm.remark"
              :rows="3"
              placeholder="请输入备注内容">
          </el-input>
        </el-form-item>

        <el-form-item label="订单项id值" prop="orderitemsIds" label-width="100px">
          <el-tag
              :key="tag"
              v-for="tag in editForm.orderitemsIds"
              closable
              :disable-transitions="false"
              @close="handleClose_Tag(tag)">
            {{ tag }}
          </el-tag>

          <el-input
              id="inin"
              v-focus
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @keydown.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 订单项id值</el-button>
        </el-form-item>

        <el-form-item label="客户id" prop="orderCustomerid" label-width="100px">
          <el-input
              v-model="editForm.orderCustomerid"
              placeholder="请输入客户id">
          </el-input>
        </el-form-item>

        <el-form-item label="状态" prop="statu" label-width="100px">
          <el-radio-group v-model="editForm.statu">
            <el-radio :label="0" v-if="hasAuth('sys:orders:update')">已创建,待审核</el-radio>
            <el-radio :label="1" v-else-if="hasAuth('sys:orders:check')">已审核,待确认出库</el-radio>
            <el-radio :label="3" v-else-if="hasAuth('sys:orders:confirm')">订单已完成</el-radio>
          </el-radio-group>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('editForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>
    <!--分页配置-->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[1,5,10, 20, 50, 100]"
        :current-page="current"
        :page-size="size"
        :total="total">
    </el-pagination>
  </div>
</template>

<script>

export default {
  directives: {
    //注册一个局部的自定义指令 v-focus,用于自动获取焦点
    focus: {
      // 指令的定义
      inserted: function (el) {
        // 聚焦元素
        el.querySelector('#inin').focus()
      }
    }
  },
  name: "Role",
  data() {
    return {
      //文件上传列表
      fileList: [],

      searchForm: {},
      delBtlStatu: true,

      total: 0,
      size: 5,
      current: 1,

      dialogVisible: false,
      dialogVisible_orderitems: false,
      editForm: {
        //订单项tag数据
        orderitemsIds: [],
      },
      inputVisible: false,
      inputValue: '',

      tableData: [],
      tableData_Dialog: [],

      editFormRules: {
        remark: [
          {required: false, message: '请输入订单备注', trigger: 'blur'}
        ],

        statu: [
          {required: true, message: '请选择状态', trigger: 'blur'}
        ],
        orderCustomerid: [
          {required: true, message: '请输入用户id', trigger: 'blur'}
        ]
      },

      multipleSelection: [],
    }
  },
  created() {
    this.getOrdersList()
  },
  methods: {
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    // 批量删除勾选,及其按钮状态设置
    handleSelectionChange(val) {
      console.log("勾选")
      console.log(val)
      this.multipleSelection = val;

      this.delBtlStatu = val.length == 0
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.size = val
      this.getOrdersList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.current = val
      this.getOrdersList()
    },

    resetForm(formName) {
      this.$refs[formName].resetFields();
      this.dialogVisible = false
      this.editForm = {}
    },
    handleClose() {
      this.resetForm('editForm')
    },

    getOrdersList() {
      this.$axios.get("/sys/orders/list", {
        params: {
          orderNum: this.searchForm.orderNum,
          current: this.current,
          size: this.size
        }
      }).then(res => {
        this.tableData = res.data.data.records
        this.size = res.data.data.size
        this.current = res.data.data.current
        this.total = res.data.data.total
      })
    },
    getOrdersExcel() {

      this.$axios.get('/sys/orders/downloadOrdersExcel', {
        responseType: 'blob'
      }).then(res => {
        let blob = new Blob([res.data], {type: 'application/vnd.ms-excel;charset=utf-8'})
        // console.log(res)
        let url = window.URL.createObjectURL(blob)
        var a = document.createElement("a")
        document.body.appendChild(a)
        a.href = url
        a.download = '全部订单信息.xlsx'
        a.click()
        window.URL.revokeObjectURL(url)
        this.$message({
          message: 'Excel导出成功',
          type: 'success',

        })
      })

    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post('/sys/orders/' + (this.editForm.orderId ? 'update' : 'save'), this.editForm)
              .then(res => {

                this.$message({
                  showClose: true,
                  message: '恭喜你，编辑或添加成功',
                  type: 'success',
                  onClose: () => {
                    this.getOrdersList()
                  }
                });

                this.dialogVisible = false
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    }
    ,
    editHandle(orderId) {
      //查询该订单的数据,回显到表单中
      this.$axios.get('/sys/orders/info/' + orderId).then(res => {
        this.editForm = res.data.data

        this.dialogVisible = true
      })
    }
    ,
    selectOrderitems(id) {
      this.$axios.get('/sys/orders/listOrderitemsById/' + id).then(res => {
        this.tableData_Dialog = res.data.data

        this.dialogVisible_orderitems = true
      })
    }
    ,
    handleClose_Tag(tag) {
      this.editForm.orderitemsIds.splice(this.editForm.orderitemsIds.indexOf(tag), 1);
    }
    ,

    showInput() {
      this.inputVisible = true;
    }
    ,

    handleInputConfirm() {
      let inputValue = this.inputValue;
      if (inputValue) {
        this.editForm.orderitemsIds.push(inputValue);
      }
      this.inputVisible = false;
      this.inputValue = '';
    }
    ,

    delHandle(id) {

      var ids = []

      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.orderId)
        })
      }

      console.log(ids)

      this.$axios.post("/sys/orders/delete", ids).then(res => {
        this.$message({
          showClose: true,
          message: '恭喜你，删除操作成功',
          type: 'success',
          onClose: () => {
            this.getOrdersList()
          }
        });
      })
    }
    ,
    checkHandle(id) {

      var ids = []

      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.orderId)
        })
      }

      console.log(ids)

      this.$axios.post("/sys/orders/check", ids).then(res => {
        this.$message({
          showClose: true,
          message: res.data.message,
          type: 'success',
          onClose: () => {
            this.getOrdersList()
          }
        });
      })
    }
    ,
    confirmHandle(id) {

      var ids = []

      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.orderId)
        })
      }

      console.log(ids)

      this.$axios.post("/sys/orders/confirm", ids).then(res => {
        this.$message({
          showClose: true,
          message: res.data.message,
          type: 'success',
          onClose: () => {
            this.getOrdersList()
          }
        });
      })
    }
    ,
    endHandle(id) {

      var ids = []

      if (id) {
        ids.push(id)
      } else {
        this.multipleSelection.forEach(row => {
          ids.push(row.orderId)
        })
      }

      console.log(ids)

      this.$axios.post("/sys/orders/end", ids).then(res => {
        this.$message({
          showClose: true,
          message: res.data.message,
          type: 'success',
          onClose: () => {
            this.getOrdersList()
          }
        });
      })
    },
    submitUpload() {
      this.$refs.upload.submit()
      // let formDate = new FormData();
      // formDate.append('file', this.uploadFiles,"file");
      //
      // this.$axios.post("/sys/orders/uploadOrdersExcel", formDate,{
      //   headers: {
      //     Authorization: localStorage.getItem("token"), 'Content-Type': 'multipart/form-data'
      //   }
      // }).then(res => {
      //   this.$message({
      //         message: "导入Excel",
      //         type: 'success',
      //         onClose: () => {
      //           this.getOrdersList()
      //         }
      //       }
      //   )
      // })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
      if (fileList.length < 1) {
        this.uploadDisabled = true //未选择文件则禁用上传按钮
      }
    },
    handleChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]] // 展示最后一次选择的文件
      }
    },
    handlePreview(file) {
      console.log(file);
    },
    // 上传文件之前的钩子：判断上传文件格式、大小等，若返回false则停止上传
    beforeUpload(file) {
      //文件类型
      const isType = file.type === 'application/vnd.ms-excel'
      const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const fileType = isType || isTypeComputer
      if (!fileType) {
        this.$message.error('上传文件只能是xls/xlsx格式！')
      }

      // 文件大小限制为10M
      const fileLimit = file.size / 1024 / 1024 < 10;
      if (!fileLimit) {
        this.$message.error('上传文件大小不超过10M！');
      }
      return fileType && fileLimit
    },
    // 自定义上传方法，param是默认参数，可以取得file文件信息，具体信息如下图
    uploadHttpRequest(param) {
      const formData = new FormData() //FormData对象，添加参数只能通过append('key', value)的形式添加
      formData.append('file', param.file) //添加文件对象
      this.$axios.post("/sys/orders/uploadOrdersExcel"
          , formData
          , {
            headers: {
              Authorization: localStorage.getItem("token"), 'Content-Type': 'multipart/form-data'
            }
          })
          .then(res => {
            const {data: {code, message}} = res
            if (code === 200) {
              param.onSuccess()  // 上传成功的文件显示绿色的对勾
            }
            this.getOrdersList()
          })
          .catch(err => {
            console.log('失败', err)
            param.onError() //上传失败的文件会从文件列表中删除
          })

    },
  }
}
</script>

<style scoped>

.el-pagination {
  float: right;
  margin-top: 22px;
}

</style>